package cn.mickey.exchange.service;

import cn.hutool.core.util.ReUtil;
import cn.mickey.exchange.domain.JsonResponse;
import cn.mickey.exchange.domain.constant.MyRegexPool;
import cn.mickey.exchange.domain.constant.UserConstant;
import cn.mickey.exchange.domain.model.UserModel;
import cn.mickey.exchange.mapper.UserMapper;
import cn.mickey.exchange.util.PageUtil;
import cn.mickey.exchange.util.RSAUtil;
import cn.mickey.exchange.util.UserUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Service
@Slf4j
public class UserService extends ServiceImpl<UserMapper, UserModel> {

    /**
     * 用户登录
     * 可以使用手机号和用户昵称登录
     *
     * @param user
     */
    public JsonResponse userLogin(UserModel user, HttpSession session) {
        if (user != null) {
            String account = user.getAccount();
            LambdaQueryWrapper<UserModel> lqw = new LambdaQueryWrapper();
            //使用账号(手机号)或者昵称登录
            if (ReUtil.isMatch(MyRegexPool.MOBILE, account)) {
                lqw.eq(UserModel::getAccount, account);
            } else {
                lqw.eq(UserModel::getNickname, account);
            }
            UserModel dbUser = baseMapper.selectOne(lqw);
            if (dbUser != null) {
                if (dbUser.getUserStatus() == 1) {
                    return JsonResponse.fail("该账号已被封禁,请联系管理员解封!");
                }
                if (UserUtil.userPasswordVerify(dbUser, user)) {
                    session.setAttribute("login_user", dbUser);
                    return new JsonResponse(dbUser, 1, "登录成功!");
                } else {
                    return JsonResponse.fail("密码错误!");
                }
            } else {
                return JsonResponse.fail("账号不存在!");
            }
        }
        return JsonResponse.fail("登录失败!");
    }

    /**
     * 用户注册
     *
     * @param user
     */
    public JsonResponse userSignIn(UserModel user) {
        user.setUserPassword(UserUtil.passwordEncrypt(user.getUserPassword()))
                .setAvatar(UserConstant.USER_DEFAULT_AVATAR);
        if (baseMapper.addUser(user) == 1) {
            return JsonResponse.success("注册成功!");
        } else {
            return JsonResponse.fail("注册失败!");
        }
    }

    /**
     * 获取通过id获取用户的信息
     */
    public JsonResponse getUserById(Long userId) {
        UserModel dbUser = baseMapper.selectOne(new LambdaQueryWrapper<UserModel>()
                .eq(UserModel::getUserId, userId));
        if (dbUser != null) {
            return JsonResponse.success(dbUser);
        }
        return JsonResponse.fail();
    }

    /**
     * 验证昵称
     *
     * @param user
     * @return
     */
    public boolean checkNickname(UserModel user) {
        UserModel dbUser = baseMapper.selectOne(new LambdaQueryWrapper<UserModel>()
                .eq(UserModel::getNickname, user.getNickname()));
        if (dbUser == null) {
            return false;
        }
        return true;
    }

    /**
     * 验证昵称和账号
     * 主要验证当前注册的昵称和账号是否存在,如果存在提示用户更换昵称或账号.
     */
    public JsonResponse checkNicknameAndAccount(UserModel user) {
        if (checkNickname(user)) {
            return JsonResponse.fail("此用户名太受欢迎,请更换一个!");
        }
        UserModel dbUser = baseMapper.getUserByAccount(user.getAccount());
        if (dbUser != null) {
            return JsonResponse.fail("该账号已经注册过,请勿重复注册！");
        }
        return JsonResponse.success();
    }

    /**
     * 修改用户密码
     */
    public boolean updatePassword(Long useId,
                                  String newPassword, String oldPassword) throws Exception {
        LambdaUpdateWrapper<UserModel> luw = new LambdaUpdateWrapper();
        UserModel dbUser = baseMapper.getUserById(useId);
        if (dbUser != null) {
            if (RSAUtil.decrypt(dbUser.getUserPassword()).equals(oldPassword)) {
                luw.set(UserModel::getUserPassword, RSAUtil.encrypt(newPassword))
                        .eq(UserModel::getUserId, useId);
                return baseMapper.update(null, luw) == 1;
            }
        }
        return false;
    }

    /**
     * 分页获取所有用户的信息
     *
     * @param params
     * @return
     */
    public JsonResponse pageListUserInfos(Map<String, Object> params) {
        String[] columns = {"account", "avatar", "nickname", "create_time", "user_status"};
        IPage result = new PageUtil().pageList(baseMapper, params, columns);
        return new JsonResponse(result);
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     */
    public boolean updateUserInfo(UserModel user) {
        UserModel newUser = new UserModel();
        newUser.setAvatar(user.getAvatar())
                .setNickname(user.getNickname())
                .setUserStatus(user.getUserStatus());
        return baseMapper.update(newUser,
                new LambdaUpdateWrapper<UserModel>().eq(UserModel::getUserId, user.getUserId())) == 1;
    }

    /**
     * 分页获取用户的状态信息
     *
     * @param status
     * @param page
     * @param num
     * @return
     */
    public Page getUserByStatus(Integer status, int page, int num) {
        LambdaQueryWrapper<UserModel> lqw = new LambdaQueryWrapper();
        lqw.select(UserModel::getUserId, UserModel::getAvatar, UserModel::getNickname, UserModel::getAccount, UserModel::getCreateTime)
                .eq(UserModel::getUserStatus, status)
                .orderByDesc(UserModel::getCreateTime);
        return baseMapper.selectPage(new Page(page, num), lqw);
    }
}
